<template>
    <el-dialog title="编辑规格"  :close-on-click-modal="false" :visible.sync="show" 
    class="dialog_index dialog_image " id="specfication" :before-close="cancle">
      <el-form v-loading="loading" label-width="68px" class="scroll"  >
        <el-tabs type="card" v-model="activeName" >
          <el-tab-pane :label="item.site" :name="item.site"  v-for="(item, i)  in formList" :key="item.id">
            <div v-for=" (spec, index) in item.data" :key="index" class="specParanet">
              <div class="specItem">
                <div class="title">
                 <span>规格{{index+1}}</span>
                 <p>
                    <el-button @click="addSpecification(index)" type="search">添加规格</el-button>
                    <el-button @click="delSpecification(index)" v-if="item.data.length !== 1">删除规格</el-button>
                    <span class="iconbtn" v-if="item.data.length !== 1">
                      <span @click="index != 0 && ramkUp(index)" :class="{'first': index == 0}"><i class="iconfont icon-rank_up"></i></span>
                      <span @click="item.data.length-1 != index && ramkDown(index)" :class="{'last': item.data.length-1 == index}"><i class="iconfont icon-rank_down"></i></span>
                    </span>
                 </p>
               </div>
            </div>
            <el-form-item label="规格名：" class="specName">
              <el-select :popper-append-to-body="false" v-model="spec.specification_name_id"  :placeholder="'规格名('+item.site+')（必填项)'" 
                @focus="(value) =>getSpecNameList(value,item) "  @change="changeSpecName(i,index)">
                <el-option v-for="item in item.specNameList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <draggable  class="specList" draggable=".specListItem"   filter=".upload-banner" 
            @end="(oldIndex,newIndex) => sortDraggable( i,index,oldIndex,newIndex)">
              <el-upload class="upload-banner specListItem" action="/api/api/general/upload" 
                :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, index)"
                  :on-error="handleBannerError" :before-upload="beforeBannerUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'product_specification', imageheight: imgH, imagewidth: imgW}" >
                  <br><el-button size="small" type="primary" @click="isFirstCloseDrawer(index)">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <p class="tip">建议上传.jpg/.jpeg/.png格式，且尺寸比例为1:1，大小≤1M</p>
              </el-upload>
              <div class="specListItem" v-for="(slide, idx) in spec.data" :key="slide.sort_key" >
                <div class="imgShow">
                  <el-image :src="slide.httpImage"></el-image>
                  <el-button @click="delSpecItem(index, idx)" class="del_item">删除</el-button>
                  <el-upload class="upload_image" action="/api/api/general/upload" 
                    :on-success="(response, file, fileList) => handleItemSuccess(response, file, fileList, index, idx)"
                    :on-error="handleBannerError" :before-upload="beforeBannerUpload"
                    :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'product_specification', imageheight: imgH, imagewidth: imgW}" >
                    <br><el-button size="small" type="primary" @click="isOtherCloseDrawer(index, idx)" class="gallery">图库选择</el-button> 
                    <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  </el-upload>
                  <p class="color_show" :style="'background-color:' + slide.color" v-if="slide.color"></p>
                </div>
                <el-input :placeholder="'亚马逊购买链接('+item.site+')（非必填项)'" disabled v-model="slide.amazon_buy_link" ></el-input>
                <el-select clearable placeholder="ASIN（非必填项）" :popper-append-to-body="false" v-model="slide.asin" @change="changeAsin(i,index,idx)" @focus="getAsinList(i,index,idx)">
                  <el-option v-for="product in item.asinList" :key="product.value" :value="product.value" :label="product.label"></el-option>
                </el-select>
                <el-select clearable placeholder="SKU全码（非必填项）" :popper-append-to-body="false" v-model="slide.sku"  @focus="getSkuList(i,index,idx)">
                  <el-option v-for="product in slide.skuList" :key="product.value" :value="product.value" :label="product.label"></el-option>
                </el-select>
                

                <div class="color_picker">
                  <el-input v-model="slide.color_name" :placeholder="'颜色名称('+item.site+')（必填项)'" >
                    <template slot="suffix" >
                      <SvgIcon iconClass="icon-color" className="picker_color"></SvgIcon>
                    </template>
                  </el-input>
                  <el-color-picker size="small" v-model="slide.color" @change="changeColorPicker(index, idx , slide.color)"></el-color-picker>
                </div>
              </div>
            </draggable>

          </div>
           
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="search" @click="submitForm" :loading="isRequest">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </span>
      <Drawer v-show="showDrawer" :type="'product_specification'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

    </el-dialog>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'
import { productSpecGet, productSpecPost, erpAsinList, get_product_sku } from '@/api/product/productBasic.js'
import { colorNameList } from '@/api/product/productColor.js'
import { specNameList } from '@/api/product/productSpecification.js'
import Drawer  from '@/components/Gallery/index.vue' 
import draggable from 'vuedraggable'

export default {
  data () {
    return {
      formList: [],
      loading: false,
      imgH: '',
      imgW: '',
      isRequest: false,
      showDrawer: false,
      isFirst: true, // 图库选择点击的位置
      index: 0,
      idx: 0,
      activeName: "US"
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number,
    row: Object
  },
  watch: {
    show:function(){
      if(this.show){
        this.isRequest = false
        this.getProductSpec()
      }
    },

  },
  methods: {
    sortDraggable (  i, index, {oldIndex,newIndex}){
      let list = this.formList
      for(let j = 0; j < list.length; j++ ){
        let data = JSON.parse(JSON.stringify(list[j].data[index].data))
        let arr = data.slice(oldIndex-1, oldIndex)[0]
        let arr2 = data.slice(newIndex-1, newIndex)[0]
        data[oldIndex-1] = arr2
        data[newIndex-1] = arr
        list[j].data[index].data = data
        this.$set(this.formList[j].data[index], 'data', data)
        
      }
      this.formList = list
    },
    isFirstCloseDrawer (index) {
      this.showDrawer = true
      this.isFirst = true
      this.index = index
    },
    isOtherCloseDrawer (index, idx) {
      this.showDrawer = true
      this.isFirst = false
      this.index = index
      this.idx = idx
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathNameHttp) { 
        let list = this.formList

        if(this.isFirst) {
          for(let i = 0 ; i < list.length; i++){
            let siteItem = list[i].data[this.index]
            let obj = {
              httpImage: data.filePathNameHttp,
              image: data.filePathName,
              specification_name: siteItem.specification_name,
              specification_key: '',
              amazon_buy_link: '',
              color: '',
              color_name: '',
              sku: '',
              product_basic_id: list[i].product_basic_id,
              site_id: list[i].id,
              site: list[i].site,
              product_id: this.id,
              id: '',
              asin: '',
              skuList: []
            }
            siteItem.data.push(obj)
          }
        } else {
          for(let i = 0 ; i < list.length; i++){
            let siteItem = list[i].data[this.index].data[this.idx]
            siteItem.httpImage= data.filePathNameHttp
            siteItem.image= data.filePathName
          }
        }
      }
    },
    // 上移
    ramkUp(index){
      let list = this.formList
      for(let i = 0; i< list.length; i++){
        let data = list[i].data
        for(let j = 0; j < data.length; j++){
          if(j == index){
            let element = data[j-1]
            this.$set(this.formList[i].data, j-1, data[j])
             this.$set(this.formList[i].data, j, element)
          }
        }
      }
    },
    //下移
    ramkDown(index){
      let list = this.formList
      for(let i = 0; i< list.length; i++){
        let data = list[i].data
        for(let j = 0; j < data.length; j++){
          if(j == index){
            let element = data[j]
            this.$set(this.formList[i].data, j, data[j+1])
             this.$set(this.formList[i].data, j+1, element)
          }
        }
      }
    },
    changeSpecName (i,index){
      let list = this.formList 
      let value = list[i].data[index].specification_name_id
      for(let m = 0 ; m<list.length; m++ ){
        let specNameList = list[m].specNameList
        for(let j = 0 ; j < list[m].data.length; j++ ){
          if(j == index){
            list[m].data[j].specification_name_id = value
            for(let k = 0 ;k < specNameList.length; k++ ){
              if(value == specNameList[k].product_id){
                list[m].data[j].specification_name =specNameList[k].label
                let colorList = list[m].data[j].data
                if(colorList ){
                  for(let q =0 ;q< colorList.length; q++){
                    colorList[q].specification_name=specNameList[k].label
                  }
                }

              }
            }
          }
        }
      }
  
      this.formList = list
    },
    // 规格下拉框
    getSpecNameList (event,item) {
      let params = {
        site_id: item.id
      }
      specNameList(params).then(res=>{
        item.specNameList = res.data
      })
    },
    // 颜色名称下拉框
    getColorName (value, callback) {
      let params = {
        color: value
      }
      colorNameList(params).then(res=>{
        let result = res.data
        callback(result)
      })
    },
    // 获取asin下拉框列表
    getAsinList(i) {
      let list = this.formList
      let params = {
        product_name: this.row.product_name,
        site: list[i].site
      }
      list[i].asinList  = []
      erpAsinList(params).then(res=>{
        list[i].asinList = res.data      
        this.formList = list
      })
    },
     // asin 改变时 亚马逊购买地址优先取存在的；不存在调用setAmazonLink拼接 sku清空
    changeAsin (i,index, idx) {
      let list = this.formList
      let curItem = list[i].data[index].data[idx]
      list[i].data[index].data[idx].sku = ''
      list[i].data[index].data[idx].skuList = []
      let asin =  list[i].data[index].data[idx].asin
      if(asin){
        let asinList = list[i].asinList
        for (let m = 0; m < asinList.length; m++) {
          if(asinList[m].value ==asin)   {
            list[i].data[index].data[idx].asin = asinList[m].value
            list[i].data[index].data[idx].amazon_buy_link = asinList[m].attribution_url 
            break
          }     
        }
        if(!curItem.amazon_buy_link) {
          list[i].data[index].data[idx].amazon_buy_link = this.setAmazonLink(list[i].site, curItem.asin)
        }
      } else {
        list[i].data[index].data[idx].amazon_buy_link = ''
      }
      this.formList = list      
    },
    // sku的下拉框列表 
    getSkuList (i,index,idx) {
      let list = this.formList
      let item = list[i].data[index].data[idx]
      let asin = item.asin
      if(asin) { 
        //  请求sku的接口
        item.skuList = []
        let params = {
          asin: asin,
          site_id: list[i].id
        }
        get_product_sku(params).then(res => {
          item.skuList = res.data      
          this.formList = list
        })
      } else {
        this.$message.error('先填写ASIN再填写SKU')
      }
    },
    // 设置亚马逊链接地址
    setAmazonLink (site,asin) {
      let link = ''
      if(asin) {
        site = site.toUpperCase() 
        if (site == 'AE') {
          link = 'https://www.amazon.ae/dp/' + asin
        } else  if (site == 'AU') {
          link = 'https://www.amazon.com.au/dp/' +asin
        } else  if (site == 'CA') {
          link = 'https://www.amazon.ca/dp/' +asin
        } else  if (site == 'DE') {
          link = 'https://www.amazon.de/dp/' +asin
        } else  if (site == 'ES') {
          link = 'https://www.amazon.es/dp/' +asin
        } else  if (site == 'FR') {
          link = 'https://www.amazon.fr/dp/' +asin
        } else  if (site == 'IT') {
          link = 'https://www.amazon.it/dp/' +asin
        } else  if (site == 'JP') {
          link = 'https://www.amazon.co.jp/dp/' +asin
        } else  if (site == 'MX') {
          link = 'https://www.amazon.com.mx/dp/' +asin
        } else  if (site == 'NL') {
          link = 'https://www.amazon.com.mx/dp/' +asin
        } else  if (site == 'UK') {
          link = 'https://www.amazon.co.uk/dp/' +asin
        } else  if (site == 'US') {
          link = 'https://www.amazon.com/dp/' +asin
        }
      }

      return link
    },
    // 删除规格
    delSpecItem (m, n) {
      let list  = this.formList 
      for(let i = 0; i< list.length; i++){
        let data =  list[i].data[m].data
        for(let j = 0; j < data.length; j++  ){
          if(n == j){
            data.splice(j, 1)
          } 
        }
      }
      this.formList  = list
    },
    // 颜色选择器改变的时候
    changeColorPicker (m, n, color){
      let that = this
       this.getColorName(color, (colorNameList)=>{
        let list  = that.formList 
        let len = colorNameList.length
        for(let i = 0; i< list.length; i++){
          let data =  list[i].data[m].data
          for(let j = 0; j < data.length; j++  ){
            if(n == j){
              data[j].color = color
             
              if (len > 0){
                for(let o = 0; o < colorNameList.length; o++) {
                  let site_id = data[j].site_id
                  if(colorNameList[o].site_id == site_id){
                    data[j].color_name = colorNameList[o].color_name
                  }
                }
              } else {
                data[j].color_name = []
              } 
            } 
          }
        }
        that.formList  = list
        if (!len){
          this.$message.error('颜色色值在【颜色管理】中不存在')
        }
      })
    
     
    },
    addSpecification (index) {
      let list  = this.formList 
      for(let i in list){
        let data =  list[i].data
        let obj = {
            specification_name: '',
            data: [ ]
          }
        data.splice(index+1, 0, obj)
      }
      this.formList  = list
    },
    delSpecification (index) {
      let list  = this.formList 
      for(let i in list){
        let data =  list[i].data
        for(let j = 0; j < data.length; j++  ){
          if(index == j){
            data.splice(j, 1)
          } 
        }
      }
      this.formList  = list
    },
    getProductSpec () {
      this.loading = true
      let params = {
        product_id: this.id
      }
      productSpecGet(params).then(res=>{
        let list = res.data
        for(let i in list){
          let dataLen = list[i].data
          list[i].asinList = []
          list[i].specNameList = []
          // this.getAsinList(i)
          if(dataLen.length  == 0) {
            let obj = {
              specification_name: '',
              specification_name_id: '',
              data: [],
            }
            let data = []
            data.push(obj)
           
            list[i].data = data
            
          }else {
            for(let m = 0; m < dataLen.length; m++ ){
              if(dataLen[m].specification_name_id) {
                dataLen[m].specification_name_id = parseInt(dataLen[m].specification_name_id)
              } else {
                dataLen[m].specification_name_id = ''
              }
              for(let q = 0; q < dataLen[m].data.length; q++){
                dataLen[m].data[q].skuList = []
              }
             
            }
          }
        }
        this.formList = list
        this.activeName= list[0].site      

        this.loading = false
        this.$nextTick(()=>{
          
          for(let i = 0; i< this.formList.length; i++){
            this.getAsinList(i)
            this.getSpecNameList(null, this.formList[i])
          }
        })
      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status ){
        this.update()
      }
    },
    validateForm () {
      let status = true
      let list = this.formList
      for (let i = 0; i < list.length; i++){
        let listData = list[i].data
        for(let j = 0; j < listData.length; j++){
          let spec = listData[j].data
          if(listData[j].specification_name_id == ''){
            this.$message.error('站点'+list[i].site+'规格' +(j+1) + '规格名为必填项')
            status = false
            return  ;
          }
          if(spec.length > 0 ){
            for(let m = 0 ; m < spec.length ; m++){
              // if(spec[m].specification_name == ''){
              //   this.$message.error('站点' + spec[m].site + '规格' +(j+1) + '规格名为必填项')
              //   status = false
              //   return  ;
              // }
              if(spec[m].image == ''){
                this.$message.error('站点' + spec[m].site + '规格' +(j+1) +'图片为必填项')
                status = false
                return 
              }
              // if(spec[m].amazon_buy_link == ''){
              //   this.$message.error('站点' + spec[m].site + '规格' +(j+1) +'下第'+(m+1)+'个亚马逊购买链接为必填项')
              //   status = false
              //   return 
              // }
              if(spec[m].color == ''){
                this.$message.error('站点' + spec[m].site + '规格' +(j+1) +'下第'+(m+1)+'个色值为必填项')
                status = false
                return 
              }
              if(spec[m].color_name == ''){
                this.$message.error('站点' + spec[m].site + '规格' +(j+1) +'下第'+(m+1)+'个颜色色值在【颜色管理】中不存在！')
                status = false
                return 
              }
            }
            } else {
              this.$message.error('规格' +(j+1) +'下至少存在一个颜色类型')
              status = false
              return 
            }
          }
      }
      return status
    },
    update () {
      if (!this.isRequest){
        this.isRequest = true
        let list = JSON.parse(JSON.stringify(this.formList)) 
        for(let i = 0; i < list.length; i++ ){
          delete list[i].asinList
          delete list[i].specNameList
          for(let j = 0; j< list[i].data.length ; j++){
            let item = list[i].data[j].data
            for(let m  = 0 ; m < item.length ; m++){
              item[m].specification_key = '规格' + (j + 1 )
              item[m].specification_name_id = list[i].data[j].specification_name_id
            }
          }
        }
        let params = {
          data: JSON.stringify(list),
          product_id: this.id
        } 
        productSpecPost(params).then(res=>{
          if(res.state == 1){
            this.$message.success('保存成功')   
            this.cancle()
          }
          this.isRequest = false
        })
      }
    },
    cancle(){
      this.$emit('closeDialog')
    },
    handleItemSuccess (response, res, fileList, index, idx) {
      console.log(res, fileList , index)
      let list = this.formList
      for(let i = 0 ; i < list.length; i++){
        let siteItem = list[i].data[index].data[idx]
        siteItem.httpImage= response.data.filePathNameHttp
        siteItem.image= response.data.filePathName
      }
      this.$message.success('上传图片成功')   
     },
    handleBannerSuccess (response, res, fileList, index) {
       console.log(res, fileList , index)
      let list = this.formList
      for(let i = 0 ; i < list.length; i++){
        let siteItem = list[i].data[index]
        let obj = {
          httpImage: response.data.filePathNameHttp,
          image: response.data.filePathName,
          specification_name: siteItem.specification_name,
          specification_key: '',
          amazon_buy_link: '',
          color: '',
          color_name: '',
          sku: '',
          product_basic_id: list[i].product_basic_id,
          site_id: list[i].id,
          site: list[i].site,
          product_id: this.id,
          id: '',
          asin: '',
          skuList: []

        }
        siteItem.data.push(obj)
      }
      this.$message.success('上传图片成功')   
    },
    handleBannerError(){
      this.$message.error('上传图片失败')   
    },
    beforeBannerUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg'&& file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          // let valid = img.width == img.height ;
          let valid = true
          let imgW = img.width
          let imgH = img.height
          if (imgW > imgH) {
            that.imgW = imgH
            that.imgH = imgH
          } else if (imgW <=  imgH) {
            imgH = imgW
            that.imgW = imgW
            that.imgH = imgW
          }
          
         
          valid ? resolve() : reject();
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        return Promise.reject()
      })
      return isSize
    },
  },
 components: { SvgIcon, Drawer, draggable },


}
</script>

<style lang="scss">
</style>